<template>
    <Breadcrumb :datas="[`管理系统`, `壁纸管理`, `壁纸分类`]">
        <el-button plain type="primary" @click="adddrawer.show = true"
            ><el-icon><Plus /></el-icon>新增分类</el-button
        >
    </Breadcrumb>
    <el-table :data="categories" style="width: 100%" empty-text="没有数据">
        <el-table-column label="分类名称" prop="name" />
        <el-table-column label="缩略图">
            <template #default="scope">
                <el-image
                    style="width: 100px"
                    :src="scope.row.thumbnail"
                    fit="cover"
                ></el-image>
            </template>
        </el-table-column>
        <el-table-column label="创建日期" prop="createdAt" />
        <el-table-column label="状态">
            <template #default="scope">
                <el-tag v-if="scope.row.isActive" type="success">已启用</el-tag>
                <el-tag type="danger" v-else>已禁用</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="图库列表">
            <template #default="scope">
                <el-link
                    type="primary"
                    @click="
                        router.replace(
                            `/wallpapers/categories/${scope.row._id}`
                        )
                    "
                >
                    <el-icon><Link /></el-icon>
                    图库列表
                </el-link>
            </template>
        </el-table-column>
        <el-table-column align="right" width="320">
            <template #header>
                <el-input
                    v-model.trim="params.keywords"
                    clearable
                    @keyup.enter="searchHandle"
                    @clear="searchHandle"
                    placeholder="请输入搜索关键词"
                    size="large"
                >
                    <template #append>
                        <el-button @click="searchHandle" size="large"
                            >搜索</el-button
                        >
                    </template>
                </el-input>
            </template>
            <template #default="scope">
                <el-switch
                    size="large"
                    style="margin-right: 10px"
                    v-model="scope.row.isActive"
                    inline-prompt
                    :active-value="false"
                    :inactive-value="true"
                    active-text="启用"
                    inactive-text="禁用"
                    @change="updateStatus(scope.row)"
                ></el-switch>
                <el-button type="primary" @click="updatepop.show = true" plain
                    >修改</el-button
                >
                <DeleteConfirm :confirm="() => deleteEvent(scope.row._id)" />
            </template>
        </el-table-column>
    </el-table>
    <div class="pagination">
        <el-pagination
            :page-size="params.pagesize"
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="params.pageno"
            :hide-on-single-page="true"
            @current-change="(page) => pageChange(page)"
        />
    </div>
    <Teleport to="body">
        <!-- 新增分类 -->
        <AddDrawer :show="adddrawer.show" title="新增分类" :close="closeDrawer">
            <template #body>
                <el-form-item label="用户名" size="large">
                    <el-input
                        v-model.trim="adddrawer.data.name"
                        type="text"
                        placeholder="请输入分类名称"
                        size="large"
                    />
                </el-form-item>
                <el-form-item label="分类缩略图" size="large">
                    <Uploader ref="addUploader" />
                </el-form-item>
            </template>
            <template #footer>
                <el-button size="large" @click="closeDrawer">取消</el-button>
                <el-button size="large" type="primary" @click="addCategory"
                    >提交</el-button
                >
            </template>
        </AddDrawer>
        <!-- 修改分类 -->
        <el-dialog
            v-model="updatepop.show"
            align-center
            width="500"
            title="分类修改"
            class="update-dialog"
        >
            <el-form label-width="80px" label-position="top">
                <el-form-item label="分类名称">
                    <el-input
                        v-model="updatepop.name"
                        size="large"
                        :prefix-icon="Notebook"
                    />
                </el-form-item>
                <el-form-item label="分类缩略图">
                    <Uploader ref="editUploader" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="large" @click="updatepop.show = false"
                    >取消</el-button
                >
                <el-button
                    size="large"
                    type="primary"
                    @click="updatepop.show = false"
                    >确定</el-button
                >
            </template>
        </el-dialog>
    </Teleport>
</template>

<script setup>
import { useRouter } from "vue-router";
import { Notebook, Plus, Link } from "@element-plus/icons-vue";
import { ref, reactive, onMounted } from "vue";
import {
    CategoryList,
    AddCategory,
    DeleteCategory,
    UpdateCategory
} from "@/api/categories";
import Breadcrumb from "@/components/breadcrumb";
import AddDrawer from "@/components/drawer";
import DeleteConfirm from "@/components/confirm";
import Uploader from "@/components/uploader";
import { ElMessage } from "element-plus";

const addUploader = ref(null);
const editUploader = ref(null);
const router = useRouter();
const adddrawer = reactive({
    show: false,
    data: {}
});

const updatepop = reactive({
    show: false,
    data: {}
});

const categories = ref([]);
const total = ref(0);
const params = reactive({
    pageno: 1,
    pagesize: 5,
    keywords: ""
});

// 关闭抽屉
const closeDrawer = () => {
    adddrawer.show = false;
};

// 确定删除
const deleteEvent = async (id) => {
    const res = await DeleteCategory(id);
    if (res) {
        ElMessage.success("删除成功");
        categories.value = categories.value.filter((item) => item._id !== id);
        total.value--;
    }
};

// 获取分类列表
const getCategories = async () => {
    const res = await CategoryList({
        pageno: params.pageno,
        pagesize: params.pagesize,
        keywords: params.keywords
    });
    if (res) {
        total.value = res.total * 1;
        categories.value = res.list;
    }
};

// 添加分类
const addCategory = async () => {
    if (!adddrawer.data.name) {
        return ElMessage.error("请输入分类名称");
    }
    if (!addUploader.value.getUrl()) {
        return ElMessage.error("请上传分类图片");
    }
    const res = await AddCategory({
        name: adddrawer.data.name,
        thumbnail: addUploader.value.getUrl()
    });
    if (res) {
        ElMessage.success("添加成功");
        categories.value.unshift(res);
        adddrawer.show = false;
        adddrawer.data = {};
        addUploader.value.clearFiles();
        total.value++;
    }
};

// 修改分类状态
const updateStatus = async ({ _id, isActive }) => {
    const status = isActive ? true : false;
    const res = await UpdateCategory(_id, { isActive: status });
    if (res) {
        ElMessage.success("分类状态修改成功");
        categories.value.map((item) => {
            if (item._id == _id) {
                item.isActive = status;
            }
        });
    }
};

// 分页
const pageChange = (pageno) => {
    params.pageno = pageno;
    getCategories();
};

// 搜索
const searchHandle = async () => {
    params.pageno = 1;
    getCategories();
};

onMounted(() => {
    getCategories();
});
</script>

<style lang="scss" scoped>
.view-drawer {
    .list {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;
        li {
            display: flex;
            img {
                width: 100%;
            }
        }
    }
}
</style>
